﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using QLMB.Models;
using QLMB.ViewModels;
using System.Web.UI.WebControls;

namespace QLMB.Controllers
{
    public class BookOfflineController : Controller
    {
        public IBookTicketRepository Repository { get; set; }

        public BookOfflineController()
            : this(new BookTicketRepository())
        {
        }

        public BookOfflineController(IBookTicketRepository repository)
        {
            Repository = repository;
        }

        [HttpGet]
        public ActionResult Index()
        {
            InfoFlight info = new InfoFlight();
            info.Ngaydi = DateTime.Now.Date;
            info.Ngayve = DateTime.Now.AddDays(1).Date;
            Repository.HamKiemTraHuyVe();
            return View(info);
        }

        [HttpPost]
        public ActionResult Index(InfoFlight info)
        {
            return RedirectToAction("ListFight", "BookOffline",
                new
                {
                    Sanbaydi = info.Sanbaydi,
                    Sanbayden = info.Sanbayden,
                    Ngaydi = info.Ngaydi,
                    Ngayve = info.Ngayve,
                    Loaive = info.Loaive,
                    SoNguoiLon = info.SoNguoiLon,
                    SoTreEm = info.SoTreEm,
                    time = 0,
                    LoaiDVdi = info.Loaidichvudi,
                    LoaiDVden = info.Loaidichvuve,
                    MaCBdi = info.MaChuyenBayDi,
                    MaCBden = info.MaChuyenBayVe
                });
        }

        [HttpGet]
        public ActionResult ListFight(string Sanbaydi, string Sanbayden, DateTime Ngaydi, DateTime Ngayve, string Loaive, int SoNguoiLon, int SoTreEm, int time, string LoaiDVdi, string LoaiDVden, string MaCBdi, string MaCBden)
        {
            IDictionary<DateTime, Decimal> GiaTuan = new Dictionary<DateTime, Decimal>();
            InfoFlight info = new InfoFlight();
            ViewBag.DSDV = Repository.LayDSCacDichVu();
            if (time == 0)
            {
                ViewBag.NGAYDI = Ngaydi;
                ViewBag.NGAYVE = Ngayve;
                ViewBag.TUADE = "Chọn lượt đi";
                info.Loaidichvuve = LoaiDVden;
                info.MaChuyenBayVe = MaCBden;
                var dscb = Repository.LayDSChuyenBay(Ngaydi, Sanbaydi, Sanbayden);
                if (dscb.Count() != 0)
                {
                    ViewBag.DSCB = dscb;
                    info.MaChuyenBayDi = ((IEnumerable<CHUYENBAY>)dscb).First().MaCB;
                    info.Loaidichvudi = Repository.LayDSCacDichVu(info.MaChuyenBayDi, info.SoTreEm + info.SoNguoiLon).First().MaLoaiDV;
                }

                for (int i = -3; i < 4; i++)
                {
                    DateTime temp = Ngaydi.AddDays(i);
                    GiaTuan.Add(temp, Repository.TimGiaThapNhatTrongNgay(temp, Sanbaydi, Sanbayden));
                }
            }
            else
            {
                ViewBag.NGAYDI = Ngayve;
                ViewBag.NGAYVE = Ngaydi;
                ViewBag.TUADE = "Chọn lượt về";
                var dscb = Repository.LayDSChuyenBay(Ngayve, Sanbayden, Sanbaydi);
                info.MaChuyenBayDi = MaCBdi;
                info.Loaidichvudi = LoaiDVdi;
                if (dscb.Count() != 0)
                {
                    ViewBag.DSCB = dscb;
                    info.MaChuyenBayVe = ((IEnumerable<CHUYENBAY>)ViewBag.DSCB).First().MaCB;
                    info.Loaidichvuve = Repository.LayDSCacDichVu(info.MaChuyenBayVe, info.SoTreEm + info.SoNguoiLon).First().MaLoaiDV;
                }

                for (int i = -3; i < 4; i++)
                {
                    DateTime temp = Ngayve.AddDays(i);
                    GiaTuan.Add(temp, Repository.TimGiaThapNhatTrongNgay(temp, Sanbayden, Sanbaydi));
                }
            }
            ViewBag.TIME = time;
            ViewBag.GiaTuan = GiaTuan;


            info.Sanbaydi = Sanbaydi;
            info.Sanbayden = Sanbayden;
            info.Ngaydi = Ngaydi;
            info.Ngayve = Ngayve;
            info.Loaive = Loaive;
            info.SoNguoiLon = SoNguoiLon;
            info.SoTreEm = SoTreEm;
            info.time = time;
            TempData["info"] = info;
            return View(info);
        }

        [HttpPost]
        public ActionResult ListFight(InfoFlight infotemp)
        {
            InfoFlight info = TempData["info"] as InfoFlight;
            if (info.time == 0)
            {
                if (info.MaChuyenBayDi != null)
                {
                    if (info.Loaive == "Khu hoi")
                    {
                        return RedirectToAction("ListFight", "BookOffline",
                        new
                        {
                            Sanbaydi = info.Sanbaydi,
                            Sanbayden = info.Sanbayden,
                            Ngaydi = info.Ngaydi,
                            Ngayve = info.Ngayve,
                            Loaive = info.Loaive,
                            SoNguoiLon = info.SoNguoiLon,
                            SoTreEm = info.SoTreEm,
                            time = 1,
                            LoaiDVdi = infotemp.Loaidichvudi,
                            LoaiDVden = infotemp.Loaidichvuve,
                            MaCBdi = infotemp.MaChuyenBayDi,
                            MaCBden = infotemp.MaChuyenBayVe
                        });
                    }
                    else
                    {
                        info.MaChuyenBayDi = infotemp.MaChuyenBayDi;
                        info.Loaidichvudi = infotemp.Loaidichvudi;
                        return RedirectToAction("InfoBooker", "BookOffline", info);
                    }
                }
                else
                {
                    TempData["info"] = info;
                    return RedirectToAction("GetBestFlight", "BookOffline");
                }
            }
            else
            {
                if (info.MaChuyenBayVe == null)
                {
                    TempData["info"] = info;
                    return RedirectToAction("GetBestFlight", "BookOffline", info);
                }
                info.Loaidichvuve = infotemp.Loaidichvuve;
                info.MaChuyenBayVe = infotemp.MaChuyenBayVe;

                return RedirectToAction("InfoBooker", "BookOffline", info);
            }
        }

        [HttpGet]
        public ActionResult GetBestFlight()
        {
            IDictionary<DateTime, CHUYENBAY> GiaThang = new Dictionary<DateTime, CHUYENBAY>();
            InfoFlight info = TempData["info"] as InfoFlight;
            DateTime now = DateTime.Now;
            if (info.time == 0)
            {
                for (int i = 0; i < 30; i++)
                {
                    DateTime temp = now.AddDays(i);
                    GiaThang.Add(temp, Repository.TimCBGiaThapNhat(temp, info.Sanbaydi, info.Sanbayden));
                }
            }
            else
            {
                for (int i = 0; i < 30; i++)
                {
                    DateTime temp = now.AddDays(i);
                    GiaThang.Add(temp, Repository.TimCBGiaThapNhat(temp, info.Sanbayden, info.Sanbaydi));
                }
            }
            if (info.time == 0)
            {
                ViewBag.NOIDI = info.Sanbaydi;
                ViewBag.NOIDEN = info.Sanbayden;
            }
            else
            {
                ViewBag.NOIDI = info.Sanbayden;
                ViewBag.NOIDEN = info.Sanbaydi;
            }
            ViewBag.NGAY = now;
            ViewBag.GIATHANG = GiaThang;
            return View(info);
        }

        [HttpGet]
        public ActionResult InfoBooker(InfoFlight info, int dif = 1)
        {
            ViewBag.CBDi = Repository.LayChuyenBay(info.MaChuyenBayDi);
            ViewBag.LoaiDVDi = Repository.LayLoaiDichVu(info.Loaidichvudi);
            ViewBag.ThueSbDi = ViewBag.CBDi.DUONGBAY.SANBAY.THUE.PhuThu;
            Decimal giadi = (ViewBag.CBDi.DUONGBAY.GiaCoBan - ViewBag.CBDi.DUONGBAY.GiaCoBan * ViewBag.CBDi.KhuyenMai / 100);
            ViewBag.TienVeDi = giadi + ViewBag.LoaiDVDi.TongTien + giadi * 5 / 100;
            ViewBag.TienThueNguoiLonDi = info.SoNguoiLon * ViewBag.ThueSbDi;
            ViewBag.TienThueTreEmDi = info.SoTreEm * ViewBag.ThueSbDi / 2;
            ViewBag.ThueVAT = ViewBag.TienVeDi * (info.SoNguoiLon + info.SoTreEm) / 10;
            info.TongTien = (info.SoNguoiLon + info.SoTreEm) * ViewBag.TienVeDi + ViewBag.TienThueNguoiLonDi + ViewBag.TienThueTreEmDi;
            if (info.Loaive == "Khu hoi")
            {
                ViewBag.CBVe = Repository.LayChuyenBay(info.MaChuyenBayVe);
                ViewBag.LoaiDVVe = Repository.LayLoaiDichVu(info.Loaidichvuve);
                ViewBag.ThueSbVe = ViewBag.CBDi.DUONGBAY.SANBAY1.THUE.PhuThu;
                Decimal giave = ViewBag.CBVe.DUONGBAY.GiaCoBan - ViewBag.CBVe.DUONGBAY.GiaCoBan * ViewBag.CBVe.KhuyenMai / 100;
                ViewBag.TienVeVe = giave + ViewBag.LoaiDVVe.TongTien + giave * 5 / 100;
                ViewBag.TienThueNguoiLonVe = info.SoNguoiLon * ViewBag.ThueSbVe;
                ViewBag.TienThueTreEmVe = info.SoTreEm * ViewBag.ThueSbVe / 2;
                ViewBag.ThueVAT += ViewBag.TienVeVe * (info.SoNguoiLon + info.SoTreEm) / 10;
                info.TongTien = info.TongTien + (info.SoNguoiLon + info.SoTreEm) * ViewBag.TienVeVe + ViewBag.TienThueNguoiLonVe + ViewBag.TienThueTreEmVe;
            }
            info.TongTien += ViewBag.ThueVAT;

            info.khdd = "-1";
            List<ListItem> items = new List<ListItem>(info.SoNguoiLon);
            items.Add(new ListItem { Text = "Chọn hành khách...", Value = "-1" });
            for (int j = 0; j < info.SoNguoiLon; j++)
            {
                items.Add(new ListItem
                {
                    Text = "Hành khách " + (j + 1).ToString(),
                    Value = j.ToString()
                });
            }
            ViewBag.SList = new SelectList(items, "Value", "Text");
            info.dsHK = new List<InfoTraveller>();
            int l = info.SoNguoiLon + info.SoTreEm;
            for (int i = 0; i < l; i++)
                info.dsHK.Add(new InfoTraveller());
            info.Nguoidat = new InfoUser();
            info.Nguoidat.NgaySinh = new DateTime(DateTime.Now.Year - 18, 1, 1);
            ViewBag.l = l;
            TempData["info"] = info;
            return View(info);
        }

        [HttpPost]
        public ActionResult InfoBooker(InfoFlight info)
        {
            InfoFlight infotemp = TempData["info"] as InfoFlight;
            info.TongTien = infotemp.TongTien;
            if(info.Nguoidat.MaHK != null)
            {
                HANHKHACHTHANTHIET hktt = Repository.LayHKTT(info.Nguoidat.MaHK);
                if (hktt != null)
                {
                    info.TongTien = (Decimal)(infotemp.TongTien - infotemp.TongTien*hktt.LOAIHK.GiamGia/100);
                }
            }
            string mave = Repository.DatVe(info);
            return RedirectToAction("Purchase", "BookOffline", new {mv = mave});
        }

        [HttpGet]
        public ActionResult Purchase(string mv)
        {
            string mave = mv;
            if (mave != null)
            {
                VECHUYENBAY vecb = Repository.LayVeChuyenBay(mave);
                return View(vecb);
            }
            else
                return View();
        }

        [HttpPost]
        public ActionResult Purchase(FormCollection collection)
        {
            Repository.ThanhToanVe(collection["MaVe"]);
            TempData["MV"] = collection["MaVe"];
            return RedirectToAction("Finish","BookOffline");

        }

        public ActionResult Finish()
        {
            ViewBag.mave = TempData["MV"] as string; 
            return View();
        }

        [HttpGet]
        public ActionResult CheckIn()
        {
            CheckIn ci = new CheckIn();
            ci.NgayDi = "Hom Nay";
            //this.Repository.CheckTime(DateTime.Now.AddHours(30));
            return View(ci);
        }

        [HttpPost]
        public ActionResult CheckIn(CheckIn ci)
        {
            VECHUYENBAY GetVeByMaVe = Repository.GetVeByMaVe(ci.Ho, ci.Ten, ci.MaVe);
            CT_VECHUYENBAY GetVeByMaCB = Repository.GetVeByMaCB(ci.Ho, ci.Ten, ci.ChuyenBay);

            if (GetVeByMaVe != null)
            {
                DateTime? Time = null;
                string NoiDi;
                if (GetVeByMaVe.LoaiVe == "Khu hoi" && GetVeByMaVe.MaTrangThaiVe == "004")
                {
                    Time = GetVeByMaVe.CT_VECHUYENBAY.Last().CHUYENBAY.NgayDi;
                    NoiDi = GetVeByMaVe.CT_VECHUYENBAY.Last().CHUYENBAY.DUONGBAY.SANBAY.MaSB;
                }
                else
                {
                    Time = GetVeByMaVe.CT_VECHUYENBAY.First().CHUYENBAY.NgayDi;
                    NoiDi = GetVeByMaVe.CT_VECHUYENBAY.First().CHUYENBAY.DUONGBAY.SANBAY.MaSB;
                }

                if (Repository.IsCheck(GetVeByMaVe.MaTrangThaiVe, GetVeByMaVe.LoaiVe) == false && ci.NoiDi == NoiDi)
                {
                    if (Repository.CheckTime((DateTime)Time) == 1 && ci.NgayDi == "Hom Nay")
                    {
                        TempData["MaVe"] = GetVeByMaVe.MaVe;
                        TempData["LoaiVe"] = GetVeByMaVe.LoaiVe;
                        TempData["SoLuong"] = (GetVeByMaVe.SoLuong).ToString();
                        return RedirectToAction("ConfirmCheckIn", "BookOffline");
                    }
                    else if (Repository.CheckTime((DateTime)Time) == 2 && ci.NgayDi == "Ngay Mai")
                    {
                        TempData["MaVe"] = GetVeByMaVe.MaVe;
                        TempData["LoaiVe"] = GetVeByMaVe.LoaiVe;
                        TempData["SoLuong"] = (GetVeByMaVe.SoLuong).ToString();
                        return RedirectToAction("ConfirmCheckIn", "BookOffline");
                    }
                    else
                    {
                        ViewBag.Message = "Quý khách vui lòng kiểm tra lại thời gian đi, Check In trong vòng 40h trước chuyến bay !";
                        return View(ci);
                    }
                }
                else
                {
                    ViewBag.Message = "Hành khách đã Check In hay thông tin nhập sai, Vui lòng kiểm tra lại !";
                    return View(ci);
                }
            }
            else if (GetVeByMaCB != null)
            {
                DateTime? Time = null;
                string NoiDi;
                if (GetVeByMaCB.VECHUYENBAY.LoaiVe == "Khu hoi" && GetVeByMaCB.VECHUYENBAY.MaTrangThaiVe == "004")
                {
                    Time = Repository.GetVeByMaVe(ci.Ho, ci.Ten, GetVeByMaCB.VECHUYENBAY.MaVe).CT_VECHUYENBAY.Last().CHUYENBAY.NgayDi;
                    NoiDi = Repository.GetVeByMaVe(ci.Ho, ci.Ten, GetVeByMaCB.VECHUYENBAY.MaVe).CT_VECHUYENBAY.Last().CHUYENBAY.DUONGBAY.SANBAY.MaSB;
                }
                else
                {
                    Time = Repository.GetVeByMaVe(ci.Ho, ci.Ten, GetVeByMaCB.VECHUYENBAY.MaVe).CT_VECHUYENBAY.First().CHUYENBAY.NgayDi;
                    NoiDi = Repository.GetVeByMaVe(ci.Ho, ci.Ten, GetVeByMaCB.VECHUYENBAY.MaVe).CT_VECHUYENBAY.First().CHUYENBAY.DUONGBAY.SANBAY.MaSB;
                }
                if (Repository.IsCheck(GetVeByMaCB.VECHUYENBAY.MaTrangThaiVe, GetVeByMaCB.VECHUYENBAY.LoaiVe) == false && ci.NoiDi == NoiDi)
                {
                    if (Repository.CheckTime((DateTime)Time) == 1 && ci.NgayDi == "Hom Nay")
                    {
                        TempData["MaVe"] = GetVeByMaCB.VECHUYENBAY.MaVe;
                        TempData["LoaiVe"] = GetVeByMaCB.VECHUYENBAY.LoaiVe;
                        TempData["SoLuong"] = (GetVeByMaCB.VECHUYENBAY.SoLuong).ToString();
                        return RedirectToAction("ConfirmCheckIn", "BookOffline");
                    }
                    else if (Repository.CheckTime((DateTime)Time) == 2 && ci.NgayDi == "Ngay Mai")
                    {
                        TempData["MaVe"] = GetVeByMaCB.VECHUYENBAY.MaVe;
                        TempData["LoaiVe"] = GetVeByMaCB.VECHUYENBAY.LoaiVe;
                        TempData["SoLuong"] = (GetVeByMaCB.VECHUYENBAY.SoLuong).ToString();
                        return RedirectToAction("ConfirmCheckIn", "BookOffline");
                    }
                    else
                    {
                        ViewBag.Message = "Quý khách vui lòng kiểm tra lại thời gian đi, Check In trong vòng 40h trước chuyến bay !";
                        return View(ci);
                    }
                }
                else
                {
                    ViewBag.Message = "Hành khách đã Check In hay thông tin nhập sai, Vui lòng kiểm tra lại !";
                    return View(ci);
                }
            }
            else
            {
                ViewBag.Message = "Quý khách vui lòng kiểm tra lại thông tin!";
                return View(ci);
            }
        }

        [HttpGet]
        public ActionResult ConfirmCheckIn()
        {
            GetInfo info = new GetInfo();
            string CInByVe = TempData["MaVe"] as string;
            string LoaiVe = TempData["LoaiVe"] as string;
            string SL = TempData["SoLuong"] as string;
            int SoLuong = int.Parse(SL);
            string MaVe;
            if (CInByVe != null)
            {
                MaVe = CInByVe;
            }
            else
            {
                CT_VECHUYENBAY CInByCB = TempData["ci"] as CT_VECHUYENBAY;
                MaVe = CInByCB.MaVe;
                LoaiVe = CInByCB.VECHUYENBAY.LoaiVe;
            }
            TempData["MaVe"] = MaVe;
            TempData["LoaiVe"] = LoaiVe;
            TempData["SoLuong"] = SL;
            //Repository.IncreaseMark("hk1");
            ViewBag.InfoHK = Repository.GetInfo(MaVe, LoaiVe, Repository.CheckStatus(MaVe), SoLuong);
            return View(info);
        }

        [HttpPost]
        public ActionResult ConfirmCheckIn(GetInfo Info)
        {
            string MaVe = TempData["MaVe"] as string;
            string LoaiVe = TempData["LoaiVe"] as string;
            string SoLuong = TempData["SoLuong"] as string;
            Repository.CIn(MaVe, Repository.CheckStatus(MaVe), LoaiVe);
            string Address = Repository.GetInfo(MaVe, LoaiVe, Repository.CheckStatus(MaVe), int.Parse(SoLuong)).First().HANHKHACH.Email;
            foreach (CT_VECHUYENBAY item in Repository.GetInfo(MaVe, LoaiVe, Repository.CheckStatus(MaVe), int.Parse(SoLuong)))
            {
                if (Repository.IsRelation(item.HANHKHACH.MaHK))
                {
                    Repository.IncreaseMark(item.HANHKHACH.HANHKHACHTHANTHIET.MaHK);
                }
            }
            Repository.CommitChanges();
            MySendMail email = new MySendMail();
            //email.SendMail_Thankyou(Address);            
            return RedirectToAction("Index", "Admin");
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult KiemTraVe(string mave)
        {
            VECHUYENBAY temp = Repository.LayVeChuyenBay(mave);
            if (temp == null)
            {
                var json = new { check = false };
                return Json(json, JsonRequestBehavior.AllowGet);
            }
            else
            {
                if(temp.LoaiVe == "Khu hoi")
                {
                    IEnumerable<string> macb = temp.CT_VECHUYENBAY.OrderBy(x=>x.CHUYENBAY.NgayDi).Select(x=>x.MaCB).Distinct();
                    var json = new
                    {
                        check = true,
                        matt = temp.MaTrangThaiVe,
                        loaive = 2,
                        Macbdi = macb.First(),
                        Macbve = macb.Last(),
                        SoNguoiDi = temp.SoLuong,
                        TongTien = temp.TongTien,
                        TenHK = temp.HANHKHACH.Ten,
                        HoHK = temp.HANHKHACH.Ho,
                        CMND = temp.HANHKHACH.CMND,
                        NgayDat = string.Format("{0: dd/MM/yyyy}",temp.NgayDatVe),
                        NgayTT = string.Format("{0: dd/MM/yyyy}", temp.NgayThanhToan)

                    };
                    return Json(json, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    string macb = temp.CT_VECHUYENBAY.Select(x => x.MaCB).Distinct().First();
                    var json = new
                    {
                        check = true,
                        matt = temp.MaTrangThaiVe,
                        loaive = 1,
                        Macbdi = macb,
                        SoNguoiDi = temp.SoLuong,
                        TongTien = temp.TongTien,
                        TenHK = temp.HANHKHACH.Ten,
                        HoHK = temp.HANHKHACH.Ho,
                        CMND = temp.HANHKHACH.CMND,
                        NgayDat = string.Format("{0: dd/MM/yyyy}", temp.NgayDatVe),
                        NgayTT = string.Format("{0: dd/MM/yyyy}", temp.NgayThanhToan)

                    };
                    return Json(json, JsonRequestBehavior.AllowGet);
                }
                
            }
        }
    }
}
